import { reqLogin, reqUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    // 存入vuex
    state.token = newToken
    // 本地存储
    setToken(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  /**
   *包装promise
   * 因为请求是异步的，我们要登录结果返回后再处理
   * 方法应该返回promise
   * .then() .catch() 或 async await
   * @param {*} context
   * @param {*} loginForm
   */
  async login(context, loginForm) {
    const res = await reqLogin(loginForm)
    // console.log(res)
    // 剥离一层数据后，去掉一个.data
    console.log(res)
    const token = res.data
    context.commit('setToken', token)
  },
  async getUserInfo({ commit }) {
    // 合并数据
    const { data: data1 } = await reqUserInfo()
    const { data: data2 } = await reqGetUserDetailById(data1.userId) // 包含头像的资料
    // const res = { ...data1, ...data2 }
    const res = Object.assign(data1, data2)
    commit('setUserInfo', res)
    return res
  },
  async logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
